<?php
class TestController extends Zend_Controller_Action
{	
    
    protected $captchaSession;
    protected $message;
    
	function init() //__construct 代替初始化函数
    {
        $this->registry = Zend_Registry::getInstance();
        $this->view = $this->registry['view'];
        $this->view->baseUrl = $this->_request->getBaseUrl();
		$this->message = new Message();
    }
    
	/*
	 * 显示
	 */
	function indexAction()
    {
		//设置每页显示数 与 获取当前页码值
		 $numPerPage = 5;
		 $getPage = $this->_request->getParam('page');
		 $page = empty($getPage)?'1':$getPage;

		$pageDbSelect=$this->message->getMessageSelect();
		$pageDbSelect->order('id DESC');                               
		$paginatorAdatper = new Zend_Paginator_Adapter_DbSelect($pageDbSelect);
        $paginator = new Zend_Paginator($paginatorAdatper);


//      //获取数据库内容        
//      $order = "id DESC";
//      $arr_message=$this->message->fetchAll(null,$order)->toArray();		
//		//factory出一个分页并且设置当前页码与每页显数
//		$paginator = Zend_Paginator::factory($arr_message);
		$paginator->setCurrentPageNumber($page)
				  ->setItemCountPerPage($numPerPage);
		//把分页显示到view
        $this->view->paginator = $paginator;
        
		echo $this->view->render('index.phtml');//显示模版
    }

    /*
	 * 新增显示/新增保存
	 */
	function addAction(){
		//如果是POST过来的值.就增加.否则就显示增加页面
		if(strtolower($_SERVER['REQUEST_METHOD'])=='post'){

			$content=$this->_request->getPost('content');
			$title=$this->_request->getPost('title');

			
			$data=array(
					'content'=>$content,
					'title'=>$title
			);
			$this->message->insert($data);
			unset($data);
			
			$this->view->prompt_msg = "新增成功！";
			$this->view->prompt_url = $this->view->baseUrl('test/index/');
			echo $this->view->render('com_prompt.phtml');

		}else{
			echo $this->view->render('add.phtml');//显示增加模版
		}
   } 


    /*
	 * 修改显示/修改保存
	 */
    public function editAction(){

	  	
		$db = $this->message->getAdapter();

		//同上面addAction
      	if(strtolower($_SERVER['REQUEST_METHOD'])=='post'){

			$content=$this->_request->getPost('content');
			$title=$this->_request->getPost('title');
			$id=$this->_request->getPost('id');
			$set=array(
					'content'=>$content,
					'title'=>$title
				);
			$where = $db->quoteInto('id = ?', $id);
			//更新表数据
			$this->message->update($set, $where);
			unset($set);
			
			$this->view->prompt_msg = "修改成功！";
			$this->view->prompt_url = $this->view->baseUrl('test/index/');
			echo $this->view->render('com_prompt.phtml');

    	 }else{

    		$id=$this->_request->getParam('id');
			//$this->view->messages=$this->message->fetchAll('id='.$id)->toArray();
			$this->view->messages=$this->message->find($id)->toArray();
    		echo $this->view->render('edit.phtml');//显示编辑模版
    	 }
    }

    

	/*
	 * 删除
	 */
	public function delAction()
	{
		
        //能过ID删除数据.这里有一些动作没有做.比如说没有ID页面要去哪里..我只是给大家一个思想..所以不会那么完整
        $id = (int)$this->_request->getParam('id');
        if ($id > 0) {
                $where = 'id = ' . $id;
                $this->message->delete($where);
         }

		$this->view->prompt_msg = "删除成功！";
		$this->view->prompt_url = $this->view->baseUrl('test/index/');
		echo $this->view->render('com_prompt.phtml');
		

	}
	
	
	/*
	 * 查询
	 */
    public function searchAction(){
       
       //设置每页显示数 与 获取当前页码值
	   $numPerPage = 5;
	   $getPage = $this->_request->getParam('page');
	   $page = empty($getPage)?'1':$getPage;	
    	
	   $title=$this->_request->getParam('k');
	   
	   
	   $pageDbSelect=$this->message->getMessageSelect();
	   $pageDbSelect->where('title like ?','%'.$title.'%')
	                ->order('id DESC');
	   $paginatorAdatper = new Zend_Paginator_Adapter_DbSelect($pageDbSelect);
       $paginator = new Zend_Paginator($paginatorAdatper);
	   
	   $paginator->setCurrentPageNumber($page)
				 ->setItemCountPerPage($numPerPage);
	   //把分页显示到view
        $this->view->paginator = $paginator;
        $this->view->title = $title;
        $this->view->isSearch = 1;
		echo $this->view->render('index.phtml');//显示模版
		
		
	}
	
	
	
	/*
	 * 验证码
	 */
	public function imgcodeAction(){
        $imagecode = new Common_Plugin_ImgCode();

        //生成图片
        //参数：字符数；字符类型（0 字母 1:数字，2：大写字母 3:小写字母 4:以上混合形式）；图片格式；图片宽；图片长
        $imagecode->image(4, 4, 'gif', 42, 22);
    }



	/*
	 * 验证码(框架自带的验证码)
	 */
	public function captchaAction(){
	       $config=new Zend_Config_Ini('./application/config/config.ini',null, true);//加载配置文件
           
           $this->captchaSession = new Zend_Session_Namespace('captcha'); //在默认构造函数里实例化
           $captcha = new Zend_Captcha_Image(
		   array('font'=>$config->captcha->captcha->font,  //字体文件路径
                 'fontsize'=>20,  //字号
                 'imgdir'=>$config->captcha->captcha->imgdir,  //验证码图片存放位置
                 'session'=>$this->captchaSession,  //验证码session值
                 'width'=>80,  //图片宽
                 'height'=>45,     //图片高
				 'DotNoiseLevel'=>0, //噪点
				 'lineNoiseLevel'=>0,  //横线数目
                 'wordlen'=>4 ));  //字母数
                 
        
			$captcha->setGcFreq(3); //设置删除生成的旧的验证码图片的随机几率
			$captcha->generate(); //生成图片
			$captcha->render();
			$this->captchaSession->code=$captcha->getWord();
			$captcha_imgpath=$captcha->getImgDir().$captcha->getId().'.png';
			header("Content-type: image/png");
			imagepng(imagecreatefrompng($captcha_imgpath)); 
			 
    }
	
	
	/*
	 * ajax验证验证码
	 */
	public function ajaxcaptchaAction(){
           $this->captchaSession = new Zend_Session_Namespace('captcha'); //在默认构造函数里实例化
		   if($this->_request->getParam('captcha_input') == $this->captchaSession->code){
		      echo "true";
		   }else{ echo "false";}
		   		 
    }
	
	

    /*
	 * 文件上传(框架自带的文件上传)
	 */
	public function uploadAction(){
           $file = new Zend_File_Transfer_Adapter_Http();
		   $file->setDestination('./public/attachments/');
		   $file->addValidator ( 'Extension', false, 'jpg,png,gif' )
			       ->addValidator( 'Size', false, 1048576*2 )
			       ->addValidator ( 'Count', false, array('min' => 1, 'max' => 3) );
			   
			if (!$file->receive()) {
			   $messages = $file->getMessages();
			   echo implode("n", $messages);
			}else{
			   //print_r($file[_files:protected][Filedata]);
			   //echo "上传成功";
			   print_r($file->getFileInfo());
			}
		   		 
    }
    
    
    
     /*
	 * 文件上传
	 */
	public function upfileAction(){
         if ($_FILES['Filedata']['name'] == '') {
			exit;
		}
		
		$uploadfile = new Common_Plugin_UploadFile();	
		$uploadfile->allow_type = array('jpg','gif','png','bmp','rar','zip','pdf','ppt','xls','txt','doc','docx','pptx','xlsx');	
		$file_ext = "";
		$file_ext = $uploadfile->_get_ext($_FILES['Filedata']['name']);	
		
		$im_width = $im_height = "";
		if (in_array(strtolower($file_ext),array('jpg','gif','png','bmp'))) {
			$file_ext = 'img';
			$r = getimagesize($_FILES['Filedata']['tmp_name']);
			$im_width = $r[0]; //图宽
			$im_height = $r[1]; //图高				
		}			
		/**
		 * 图片大小缩略
		 */
		if ($im_width > 600 && $file_ext == 'img') {
			$im_height_pre = 600/$im_width;
			$uploadfile->ifresize = true;
			$uploadfile->resize_width = 600;
			$uploadfile->resize_height = $im_height*$im_height_pre;			
		}			
		$filename = $uploadfile->upfile('Filedata');
		
	
		/**
		 * 上传后的信息输出到页面
		 */
		echo $_FILES["Filedata"]['name']."|".$filename['getfilename']."|".$file_ext;			
		exit;			
		   		 
    }
	
	
	
	
	/*
	 * Zend_Mail发送邮件
	 */
	public function zendmailAction(){
        $config=new Zend_Config_Ini('./application/config/config.ini',null, true);//加载配置文件
         
		 $configInfo = array('auth' => 'login',  
                             'username' => $config->mail->mail->fromemail,  
                             'password' => $config->mail->mail->password,  
                             'port' => $config->mail->mail->port); 
		 
        $smtpHost = new Zend_Mail_Transport_Smtp($config->mail->mail->server,$configInfo);  
         //Create Zend_Mail object.  
         $MailObj = new Zend_Mail();  
         //Initialize parameters.  
         $emailMessage = "Hey, this is a Zend_Mail–created e-mail!";  
         $fromEmail = $config->mail->mail->fromemail;  
         $fromFullName = $config->mail->mail->username;  
         $to = "86529448@qq.com";  
         $subject = "This is an example";  
         $MailObj->setBodyText($emailMessage);  
         $MailObj->setFrom($fromEmail, $fromFullName);  
         $MailObj->addTo($to);  
         $MailObj->setSubject($subject);  
           
         //Send Email using transport protocol.  
         try{  
             $MailObj->send($smtpHost);  
             echo "Email sent successfully";  
         }catch(Zend_Mail_Exception $e){  
             //Your error message here.  
             echo 'error';  
             echo $e->getMessage();  
         }  
         		   		 
    }
    
    


	
}
	
	
	